//
//  EditTimelineViewController.m
//  WeCommunity
//
//  Created by mac on 2017/6/16.
//  Copyright © 2017年 lzy. All rights reserved.
//

#import "EditTimelineViewController.h"
#import "EditDynamicContentView.h"
#import "PhotoAlbumViewController.h"
#import "PhotoAlbumHelper.h"
#import "PhotoAlbumModel.h"

#import "TopDropDownBtnView.h"
#import "EditChooseTypeView.h"
#import "CommunityLinkServer.h"

@interface EditTimelineViewController ()<EditToolBarDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,EditDynamicContentDelegate,TopDropDownBtnDelegate,EditChooseTypeDelegate>

@property (nonatomic,strong) UIBarButtonItem * rightBtnItem;

@property (nonatomic,strong) EditDynamicContentView * editView;

@property (nonatomic,strong) TopDropDownBtnView * dropDownBtnView;

@property (nonatomic,strong) EditChooseTypeView * editChooseView;

@property (nonatomic,assign) BOOL editChooseViewIsShow;

@property (nonatomic,strong) NSString * addLinkUrl;

@property (nonatomic,strong) NSArray * chooseTypeDataSource;

@property (nonatomic,strong) NSMutableArray * imageDataSource;



@end

@implementation EditTimelineViewController

#pragma mark - get
-(UIBarButtonItem *)rightBtnItem
{
    if (!_rightBtnItem) {
        _rightBtnItem = [[UIBarButtonItem alloc] initWithTitle:KNSLocal(@"sendTitle") style:UIBarButtonItemStylePlain target:self action:@selector(sendData)];
        [_rightBtnItem setTitleTextAttributes:@{NSFontAttributeName:PFR_FONT(16), NSForegroundColorAttributeName :TINT_GREEN_COLOR} forState:UIControlStateNormal];
    }
    return _rightBtnItem;
}

-(EditDynamicContentView *)editView
{
    if (!_editView) {
        _editView = [[EditDynamicContentView alloc] initWithFrame:CGRectMake(0, 0, KScreen_Width, KScreen_Height - KNaviheight) timeLineType:self.timeLineType];
        _editView.delegate = self;
        _editView.editDelegate = self;
    }
    return _editView;
}

-(TopDropDownBtnView *)dropDownBtnView
{
    if (!_dropDownBtnView) {
        _dropDownBtnView = [[TopDropDownBtnView alloc] initWithFrame:CGRectMake(0, 0, KScreen_Width - 128, 44)];
        _dropDownBtnView.delegate = self;
    }
    return _dropDownBtnView;
}

-(EditChooseTypeView *)editChooseView
{
    if (!_editChooseView) {
        _editChooseView = [[EditChooseTypeView alloc] initWithFrame:self.view.bounds];
        _editChooseView.delegate = self;
        [_editChooseView setContentTitles:[self.chooseTypeDataSource copy] selectedIndex:self.dataType];
        [self.view addSubview:_editChooseView];
    }
    
    [self.view bringSubviewToFront:_editChooseView];
    
    return _editChooseView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initWithData];
    
    [self initWithUserInterface];
    
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if (!self.editChooseViewIsShow) {
        [self.editView startEditing];
        
        [self verifyDynamicContentStatus];
    }
}

-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
    [self.editView endEditing];
}


-(void)initWithUserInterface
{
//    self.title = KNSLocal(@"published");
    
    self.navigationItem.titleView = self.dropDownBtnView;
    
    [self.dropDownBtnView setContentValue:self.chooseTypeDataSource[self.dataType]];
    
    
    self.navigationItem.rightBarButtonItem = self.rightBtnItem;

    [self.view addSubview:self.editView];
}

-(void)initWithData
{
    self.imageDataSource = [NSMutableArray array];

    if (self.timeLineType == TimeLineType_dynamic) {
        self.chooseTypeDataSource = @[KNSLocal(@"护肤"),KNSLocal(@"美妆"),KNSLocal(@"生活"),
                                      KNSLocal(@"服饰"),KNSLocal(@"食品"),KNSLocal(@"保健"),
                                      KNSLocal(@"其他")];
    }else if (self.timeLineType == TimeLineType_community){
        self.chooseTypeDataSource = @[KNSLocal(@"综合"),KNSLocal(@"入门"),KNSLocal(@"客源"),
                                      KNSLocal(@"货源"),KNSLocal(@"销售"),KNSLocal(@"代理"),
                                      KNSLocal(@"其他")];
    }
}

#pragma mark - delegate
-(void)editDynamicContentWithContent:(NSString *)content
{
    [self verifyDynamicContentStatus];
}

#pragma mark - 选择照片、拍照
-(void)editToolBarSeletedIndex:(NSInteger)index
{
    if (![self canProcessNext]) {
        return;
    }
    if (index == 0) {
        //相册
        PhotoAlbumViewController * photoAlbumVC = [[PhotoAlbumViewController alloc] init];
        photoAlbumVC.originalDataSource = self.imageDataSource;
        
        if (self.timeLineType == TimeLineType_dynamic) {
            photoAlbumVC.maxPhotoCount = 9;
        }else if (self.timeLineType == TimeLineType_community){
            photoAlbumVC.maxPhotoCount = 1;
        }
        
        RootNaviViewController * nav = [[RootNaviViewController alloc] initWithRootViewController:photoAlbumVC];
        nav.navigationBar.translucent = NO;//设置不透明
        nav.navigationBar.barTintColor = NAVC_COLOR; //导航条颜色
        nav.navigationBar.tintColor = WHITE_COLOR;  //导航条字体颜色
        [self presentViewController:nav animated:YES completion:nil];
        
        @weakify(self);
        [photoAlbumVC photoAlbumChooseComplete:^(NSMutableArray *results) {
            @strongify(self);
            //选完照片
            self.imageDataSource = [results mutableCopy];
            [self.editView loadAssetsArray:self.imageDataSource];
            
            [self verifyDynamicContentStatus];
        }];
    }else if (index == 1){
        
        if (self.timeLineType == TimeLineType_dynamic) {
            if (self.imageDataSource.count == 9) {
                return;
            }
        }else if (self.timeLineType == TimeLineType_community){
            if (self.imageDataSource.count == 1) {
                return;
            }
        }
        //拍照
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            UIImagePickerController *pickerController = [[UIImagePickerController alloc]init];
            pickerController.allowsEditing = NO;
            pickerController.delegate = self;
            pickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:pickerController animated:YES completion:^{
                
            }];
        }
    }else if (index == 2){
        //发表网址
        [self systemAlertWithTitle:@"管理员发表内容"
                        andMessage:@"请输入内容网址链接"
                          needText:YES
                           content:self.addLinkUrl
                       placeholder:@"网址链接"
                     needNumberPad:NO
                     actionTextOne:@"取消"
                     actionTextTwo:@"确定"
                    actionOneBlock:^{
                        [self verifyDynamicContentStatus];
                    } actionTwoBlock:^(NSString *text) {
                        self.addLinkUrl = text;
                        [self verifyDynamicContentStatus];
                    }];
    }
}

#pragma mark- UIImagePickerViewController 拍照完成
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    @weakify(self);
    //存到系统相册
    [[PhotoAlbumHelper shared] saveImage:image
                                         toAlbum:nil
                                 completionBlock:^(ALAsset *asset, NSError *error) {
                                     @strongify(self);
                                     if (error == nil && asset) {
                                         PhotoAlbumModel * model = [PhotoAlbumModel new];
                                         model.asset = asset ;
                                         [self.imageDataSource addObject:model];
                                         [self.editView loadAssetsArray:self.imageDataSource];
                                         [self verifyDynamicContentStatus];
                                     }
                                 }];
    
    [picker dismissViewControllerAnimated:NO completion:^{}];
}

#pragma mark -  顶部选择按钮
-(void)dropDownBtnSelected:(BOOL)selected
{
    [self.editChooseView setChooseViewAnimationWithShow:selected animation:YES];
    self.editChooseViewIsShow = selected;
    if(selected){
        [self.editView endEditing];
        [self setSendItemIsOk:NO];
    }else{
        [self.editView startEditing];
        [self verifyDynamicContentStatus];
    }
}

#pragma mark -  顶部选择view
-(void)editChooseViewSelectedTitle:(NSString *)title selectedIndex:(NSInteger)index
{
    self.dataType = index;
    [self.dropDownBtnView setContentValue:self.chooseTypeDataSource[self.dataType]];
}

#pragma mark - 发送
-(void)sendData
{
    [self showLoadingHudWithHText:KNSLocal(@"publishing")];
    [self setSendItemIsOk:NO];
    [self.editView hiddenKeyBoard];
    
    PostDynamicModel * postModel = [PostDynamicModel new];
    postModel.content = self.editView.textView.text;
    postModel.imagelist = self.imageDataSource;
    postModel.dataType = (int)self.dataType;
    postModel.addLinkUrl = self.addLinkUrl;
    
    if (self.timeLineType == TimeLineType_dynamic) {
        @weakify(self);
        [[DynamicServer shared] postDynamicWithModel:postModel complete:^(BOOL success, NSString *error) {
            @strongify(self);
            [self hiddenLoadingHud];
            if (error) {
                [self sureAlertWithTitle:nil andMesg:error];
            }else{
                if (![UserInfoManger shared].isRemovedAD) {
                    //更新用户的积分
                    [[UserInfoManger shared] addCoins:[NSNumber numberWithInteger:-10] complete:^(BOOL success, NSString *error) {
                        
                    }];
                }
                //发送完毕回到首页
                if ([self.delegate respondsToSelector:@selector(sendTimeLineContentDoneWithIndex:)]) {
                    [self.delegate sendTimeLineContentDoneWithIndex:0];
                }
                [self.navigationController popViewControllerAnimated:YES];
            }
        }];
    }else if (self.timeLineType == TimeLineType_community){
        @weakify(self);
        [[CommunityLinkServer shared] postCommunityWithModel:postModel complete:^(BOOL success, NSString *error) {
            @strongify(self);
            [self hiddenLoadingHud];
            if (error) {
                [self sureAlertWithTitle:nil andMesg:error];
            }else{
                //发送完毕回到首页
                if ([self.delegate respondsToSelector:@selector(sendTimeLineContentDoneWithIndex:)]) {
                    [self.delegate sendTimeLineContentDoneWithIndex:0];
                }
                [self.navigationController popViewControllerAnimated:YES];
            }
        }];
    }
}

-(void)verifyDynamicContentStatus
{
    if (self.timeLineType == TimeLineType_dynamic) {
        if (self.editView.textView.text.length > 0 || self.imageDataSource.count > 0) {
            [self setSendItemIsOk:YES];
        }else{
            [self setSendItemIsOk:NO];
        }
    }else if (self.timeLineType == TimeLineType_community){
        if (self.editView.textView.text.length > 0 && self.imageDataSource.count > 0 && self.addLinkUrl.length > 0) {
            [self setSendItemIsOk:YES];
        }else{
            [self setSendItemIsOk:NO];
        }
    }
}

-(void)setSendItemIsOk:(BOOL)ok
{
    if (ok) {
        self.rightBtnItem.enabled = YES;
        [self.rightBtnItem setTitleTextAttributes:@{NSFontAttributeName:PFR_FONT(16), NSForegroundColorAttributeName :TINT_GREEN_COLOR} forState:UIControlStateNormal];
    }else{
        self.rightBtnItem.enabled = NO;
        [self.rightBtnItem setTitleTextAttributes:@{NSFontAttributeName:PFR_FONT(16), NSForegroundColorAttributeName :TINT_GREEN_TR_COLOR} forState:UIControlStateNormal];
    }
}


@end
